;
(function() {

	Array.prototype.removeRepeatBuildingAndFLoor = function () {
	  var res = [this[0]];
	  for (var i = 1; i < this.length; i++) {
	    var repeat = false;
	    for (var j = 0; j < res.length; j++) {
	      if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
	        repeat = true;
	      }
	    }
	    if (!repeat) {
	      res.push(this[i]);
	    }
	  }
	  return res;
	};

  new Vue({
    el: '#contract-update',
    data: {
      tabData:[
        {'name':'合同信息' },
        // {'name':'账单变更信息' },
      ],
      tabSelectedIndex:0,
      data: {'alterInfoVO':{}, commissionRules: [],expenses:[]},
			contract:'',
			rent:[],
      history:{'alterHistory':[]},
      building:[],  // 楼宇数据
      selectedTabItem: '合同信息',
      loadContractMesModule: true,
      loadHistoryModule: false,
      permissions: JSON.parse(localStorage.getItem('permissions')),
      alterId: hlUrlUtil.GetQueryString('id'),
      contractId:hlUrlUtil.GetQueryString('contractId'),
      isShowSubmitLayer: false,
      submitLayerData: {
        companyName: '',
        beginDate: '',
        endDate: '',
        id: ''
      },
			resourceMes:{
			  st: [],
			  ot: []
			},   // 资源信息
			building:[],  // 楼宇数据
			totalArea:0,
			unit:[], // 单元
			st: [], // 车位
			wp: [], // 工位
      delFlag: false,
			pExpense: [],
			oExpense: [],
			tExpense: [],
      industryTypes: {list: []},
			unitId: null, // 单元id
			unitDetailsFlag: false,
			payData: [],
			versionDisplay: false,
			groupLogs: [],
			publicGroup: ['Y', 'N'],
			publicFlag: ['Y', 'N'],
			publicLogsTypes: ['text', 'value', 'change', 'delete'],
			cutChangeFlowFlag: false,
			billChangeData: {conflictBills: [], confilctSettleUpBill: {billExpense: []}},
			tmpData: [],
			freeDate:[],
			alertFile:[],
			moneyCha:0,
			conflictBills:'',
			effectiveRD:'',
			effectiveRM:'',
			breakPriceFlag:''
    },
    filters: {
      formatDate: function(time) {
        if (time === undefined)return '--'

				console.log(hlDateUtil)
				
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
			formAlterType (item) {
				let res = '';
				switch (item){
					case 'ALL':
						res = '基本信息变更;条款变更'
						break;
					case 'YB':
						res = '基本信息变更'
						break;
					case 'CW':
						res = '条款变更'
						break;
					default:
						res = '--'
						break;
				}
				return res
			},
      formatDetailDate:function (time) {
        if (time === undefined) return '--'
        return hlDateUtil.formatUTCDate(time)
      },
      formatUndefined: function(item) {
        if (!item)return '--'
        return item
      },
      formatIndustry: function(item) {
        return hlCodeConvert.industryType(item)
      },
      formatZlfType:function(item){
        return hlCodeConvert.contractZlfType(item)
      },
      formatContractType:function(item){
        return hlCodeConvert.contractType(item)
      },
      formatContractAuditState:function(item){
        return hlCodeConvert.contractAuditState(item)
      },
      formatNum: function(item) {
        return hlNumberUtil.formatNum(item)
      }
    },
    computed: {
      ityName: function () {
        var result;
        var self = this;
        this.industryTypes.list.map(function (item) {
          if (self.data.zlfIndustryType == item.dictCode) {
            result = item.dictName;
          }
        })
        return result;
			},
			dototal: function () {
				var result = 0;
        this.data.expenses.map(function (item) {
          if (item.expenseType == 'D') {
            result++
          }
				})
				return result
      },
			yaTotal(){
				let num = 0
        this.data.expenses.map(item =>{
          if(item.expenseType == 'D'){
            num = num + Number(item.amount)
          }
        })
        return num.toFixed(2)
      }
    },
    methods: {
		formatDate: function(time) {
			if (time === undefined)return '#'
			return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
		  },
		// 获取破底价配置
			getBreakPrice(){
				hlhttp.get({
					url: 'configure/dict',
					data: {
						'module_code': 'CIWU',
						'config_name': 'CW_BREAK_PRICE_REMINDER_TYPE_CONFIG'
					},
					success: res => {
						// CONTRASTPRICE 与预签约单价比较
						// CONTRASTRENT  与有效租金比较
						this.breakPriceFlag = res[0].dictValue == 'CONTRASTRENT'? 'CR':'CP'
					}
				})
			},

		// 判断价格是否符合底价策略
		isSatisfyMinPrice:function(){
			var self = this;
			let arr = self.$refs.payData.subtotalArr.R || []
			let contract_amount = ''
			arr.map(item =>{
				if(item.name == "固定租金"){
					contract_amount = item.expense
				}
			})
			console.log(contract_amount,'contract_amount');
			// 所选合同类型  WP 工位   UN 单元
			var type = self.contract.contractType === 'WR' ? 'WP' : 'UN'
			// 所选单元或者工位id  如果只选车位 则不掉用底价策略
			var getUnitIds = function(){
			  var res = [];
			  self.unit.map(function(_item){
				res.push(_item.unitId)
			  })
			  res = hlArrayUtil.arrUnique(res)
			  return res.join()
			}
			var getWpIds = function(){
			  var res = [];
			  self.wp.map(function(item){
				item.positions.map(function(_item){
				  res.push(_item.positionId)
				})
			  })
			  res = hlArrayUtil.arrUnique(res)
			  return res.join()
			}
			var ids = null;
			if(type === 'WP'){ ids = getWpIds()}
			if(type === 'UN'){ ids = getUnitIds()}
			// 日租金、月租金计算
			var acreage = self.totalArea ? self.totalArea : this.wpTotalNum;
			var rentPriceDay = self.contract.rentPriceDay / acreage;
			console.log(rentPriceDay,'rentPriceDay');
			var rentPriceMonth = self.contract.rentPriceMonth / acreage
			var data = {
				rent_price_day:Number(rentPriceDay).toFixed(2),
				rent_price_month:Number(rentPriceMonth).toFixed(2),
				type:type,
				ids:self.contract.units[0].unitId,
				policy_type:self.breakPriceFlag || '#',
				contract_amount:contract_amount+'' || '#',
				contract_begin_date:self.formatDate(self.contract.beginDate) || '#',
				contract_end_date:self.formatDate(self.contract.endDate) || '#',
			  }	
			  hlhttp.put({
				url:'check_base_price_policy',
				data,
				success:function(data){
				  self.effectiveRD = data.effectiveRentDay
				  self.effectiveRM = data.effectiveRentMonth
				}
			  })
		  },

			//只显示变更信息
			cutChangeFlow () {
				this.cutChangeFlowFlag = !this.cutChangeFlowFlag;
				if (this.cutChangeFlowFlag) {
					this.publicLogsTypes = ['change', 'delete']
					this.publicGroup = ['Y']
					this.publicFlag = ['Y']
				}
				if (!this.cutChangeFlowFlag) {
					this.publicLogsTypes = ['text', 'value', 'change', 'delete']
					this.publicGroup = ['Y', 'N']
					this.publicFlag = ['Y', 'N']
				}
			},
			versionevent () {
				this.versionDisplay = !this.versionDisplay;
				if (this.versionDisplay) {
					hlhttp.get({
						url: 'contract_history/_contrast/alter_id',
						data: {alter_id: this.alterId},
						success: (data) => {
							let type = ['add', 'change', 'delete']
							data.groupLogs.map(item => {
								item.group = 'N'
								item.logRecords.map(item1 => {
									item1.rowData.map(item2 => {
										if (type.indexOf(item2.logType) >= 0) {
											item.group = 'Y'
										}
									})
								})
							})
							this.groupLogs = data.groupLogs;
						}
					})
				}
			},

      getData:function(){
        var self = this;
        hlhttp.get({
          url: 'contract_history',
          data:{'alter_id':self.alterId},
          success: function (data) {
						if(data.alterInfoVO.agreementFlag == 'Y'){
							let names = data.alterInfoVO.agreementAttachmentNames.split(',')
							let urls = data.alterInfoVO.agreementAttachmentUrls.split(',')
							names.map((item,index) =>{
								self.alertFile.push({
									name:item,
									url:urls[index]
								})
							})
						}


						if (data.alterInfoVO.alterType != 'YB') {
							self.tabData = [
							  {'name':'合同信息' },
							  {'name':'账单变更信息' },
							]
						}
						
						self.tmpData = data.pageCustomizeComponentBizContentList ? data.pageCustomizeComponentBizContentList : []

						self.billChangeInfo(data.alterInfoVO.alterId)
						// 单元
						var buildingData = self.unitData(data.units)
						self.totalArea = data.rentAcreage
						console.log(buildingData.building)
						self.building = buildingData.building
						// 车位
						self.st = [];
						self.wp = [];
						var stTotalNum = 0;
						var wpTotalNum = 0;
						data.units.map(function (item) {
						  if (item.positions && item.unitType === 'ST') {
						    stTotalNum = stTotalNum + item.positions.length;
						    item['num'] = item.positions.length;
						    self.st.push(item)
						  }
						  if (item.positions && item.unitType === 'WP') {
						    wpTotalNum = wpTotalNum + item.positions.length;
						    item['num'] = item.positions.length;
						    self.wp.push(item)
						  }
						})
						self.stTotalNum = stTotalNum;
						self.wpTotalNum = wpTotalNum;
						if (!data.commissionRules) {
						  data.commissionRules = []
						}
						// 租金数据
						self.rent = [];
						if (data.rentIncreseDate && data.rentIncreseDate.split(',').length > 1) {
						  for (var i = 1; i < data.rentIncreseDate.split(',').length; i++) {
						    self.rent.push({
						      beginDate: data.rentIncreseDate.split(',')[i],
						      percent: data.rentIncresePercent.split(',')[i] ? data.rentIncresePercent.split(',')[i] : '',
						      price: data.rentIncresePrice ? data.rentIncresePrice.split(',')[i] : '',
						      dayPrice: data.rentIncreseDay ? data.rentIncreseDay.split(',')[i] : '',
						      monthPrice: data.rentIncreseMonth ? data.rentIncreseMonth.split(',')[i] : ''
						    })
						  }
						}
						// 折扣月租金
            if (data.rentIncreseDiscountDay) {
              let arr1 = data.rentIncreseDiscountRate.split(',')
              let arr2 = data.rentIncreseDiscountDay.split(',')
              let arr3 = data.rentIncreseDiscountMonth.split(',')
              self.rent.map((item, index) => {
                item.discount = arr1[index + 1]
                item.discountD = arr2[index + 1]
                item.discountM = arr3[index + 1]
              })
            }
						// 合同免租期
						self.freeDate = [];
						if (data.freeDates) {
							self.freeDate = data.freeDates
						}
						// 费用数据
						self.pExpense = [];
						self.oExpense = [];
						self.tExpense = [];
						if (data.expenses) {
						  for (var j = 0; j < data.expenses.length; j++) {
						    if (data.expenses[j].expenseType == 'P') {
						      self.pExpense.push(data.expenses[j])
						    }
						    if (data.expenses[j].expenseType == 'O') {
						      self.oExpense.push(data.expenses[j])
						    }
						    if (data.expenses[j].expenseType == 'T') {
						      self.tExpense.push(data.expenses[j])
						    }
						  }
						}

            self.data = data;
            self.contract = data;
			// setTimeout 的作用是让 self.$refs.payData.subtotalArr.R 拿到数据
			setTimeout(()=>{
				self.isSatisfyMinPrice()
			},300)

          }
        })
      },
			// 付款计划数据处理
			dealWithbillData:function () {
			  var self = this;
			  hlhttp.get({
			    url: 'contract_alter/bill_plans',
			    data: {contract_alter_id:self.alterId},
			    success: function(data) {
						//千万别动付款计划，否则死路一条，代码千奇百怪
						let newData = [...data.billPlan, ...data.addedBillPlan]
						self.payData = newData;
						
			    }
			  })
			},
			// 导出账单
			exportBill:function () {
			  var self = this;
			  $.ajax({
			    url: exclUrl+'resource/bill_excel',
			    type: 'get',
			    headers: {token: Cookies.get("token")},
			    data: {contract_id: self.contractId},
			    success: function (res) {
			      var a = document.createElement('a');
			      a.href = res.excel_url;
			      $('body').append($(a))
			      a.click();
			      setTimeout(function() {
			        $(a).remove()
			      }, 100);
			    }
			  })
			},
			// 获取单元详情
			getUnitDetails: function (unitId) {
			  var self = this;
			  self.unitId = unitId;
			  self.unitDetailsFlag = true;
			},
			closeUnitPop: function (state) {
			  this.unitId = null;
			  this.unitDetailsFlag = false;
			},
			//工位车位处理
			unitData: function (unitsData) {
			  // 去除含有工位车位的单元
			  var units = [];
			  unitsData.map(function (_item) {
			    if (_item.positions.length === 0) {
			      units.push(_item)
			    }
			  })
			  if (units.length === 0) {
			    return {
			      building: [],
			      totalArea: 0
			    }
			  }
			  // 合并单元项
			  var unit = [];
			  var totalArea = 0;
			  for (var i = 0; i < units.length; i++) {
			    unit.push({
			      buildingName: units[i].buildingName,
			      floorNum: units[i].floorNum,
			      floorName: units[i].floorName,
			      unit: [],
			      unitId: []
			    })
			  }
			  var unitArr = unit.removeRepeatBuildingAndFLoor()
			  for (var z = 0; z < unitArr.length; z++) {
			    for (var m = 0; m < units.length; m++) {
			      if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
			        unitArr[z].unit.push(units[m].unitName + '(' + hlNumberUtil.formatNum(units[m].unitAcreage) + 'm²)')
			        unitArr[z].unitId.push(units[m].unitId)
			        totalArea = totalArea + Number(units[m].unitAcreage)
			      }
			    }
			  }
			  // 合并楼层项
			  var building = [];
			  for (var j = 0; j < unitArr.length; j++) {
			    building.push({
			      buildingName: unitArr[j].buildingName,
			      floor: []
			    })
			  }
			  var buildingArr = hlArrayUtil.removeRepeat(building, 'buildingName')
			  for (var k = 0; k < buildingArr.length; k++) {
			    for (var n = 0; n < unitArr.length; n++) {
			      if (unitArr[n].buildingName == buildingArr[k].buildingName) {
			        buildingArr[k].floor.push({
			          'floorNum': unitArr[n].floorNum,
			          'floorName': unitArr[n].floorName,
			          'unit': unitArr[n].unit,
			          'unitId': unitArr[n].unitId
			        })
			      }
			    }
			  }
			  return {
			    building: buildingArr,
			    totalArea: totalArea
			  }
			},
      //获取行业列表
      getIndustryTypes: function () {
        var self = this;
        hlhttp.get({
          url: 'configure/industry/dict',
          success: function (data) {
            self.industryTypes.list = data;
            self.getData()
          }
        })
      },
      //删除合同
      delContract: function() {
        var _this = this;
        hlhttp.delete({
          url: 'contract?contract_id=' + _this.contractId,
          success: function() {
            _this.delFlag = false;
            hl.toast('删除成功')
            hlUrlUtil.goTo('contract', {ddtab:true})
          }
        })
      },
      handleSelectedTab: function(val, i) {
        const {name,isDisabled} = val
        this.selectedTabItem = name
      },
      // 编辑合同
      editContract: function() {
        var self = this;
        // 草稿状态才能编辑  进入变更合同编辑页面
        hlUrlUtil.goTo('contractChangeIndex', {id: this.contractId, alertId: this.alterId, code: this.data.alterInfoVO.alterNo, ddtab:true, mode: 'edit'},true)
      },
      // 作废合同
      invalidContract: function() {
        var self = this;
        hllayer.confirm1('此操作不可逆转，确定作废变更单吗？', function() {
          hlhttp.put({
            url: 'contract_alter/_cancel',
            data: { "alter_id": self.alterId },
            success: function(data) {
              self.getData()
            }
          })
        })
      },
      // 提交合同
      submitContract: function() {
				var self = this;
        hllayer.confirm1('此操作不可逆转，变更内容将立即生效！', function() {
          hlhttp.put({
            url: 'contract_history/details_submit',
            data: { alter_id: self.alterId },
            success: function(data) {
              self.getData()
            }
          })
        })
      },

			// 获取账单变更信息
			billChangeInfo (id) {
				hlhttp.get({
					url: 'bill/alter_info',
					data: {contract_alter_id: id},
					success: (data) => {
						if (!data.confilctSettleUpBill) {
							data.confilctSettleUpBill = {billExpense: [], totalAmountReceive: 0}
						}
						this.billChangeData = data;
						this.conflictBills = data.conflictBills
						let ex = data.conflictBills[0].expenses[0].withdrawAmount
						this.moneyCha = (ex.amountPayed*1 + ex.derateExpense*1 + ex.carryOverAmount*1 - ex.amountReceive*1).toFixed(2) 
					}
				})
			}
    },
    mounted: function() {
    	this.getIndustryTypes()
		this.dealWithbillData()
		this.getBreakPrice()
    }
  })
}())
